package JF;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

import static org.apache.hadoop.io.NullWritable.*;
//v1.4 change output&input format, plus test
//v1.5 string bug found, standard output format
public class BasicFriends {

    public static class BasicFriendsStepOneMapper extends Mapper<LongWritable, Text,Text,Text> {
        Text k = new Text();
        Text v = new Text();
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            final String line = value.toString();

            final String[] userAndFriends = line.split(", ");
            String user = userAndFriends[0];    //user
            final String[] friends = userAndFriends[1].split(" ");  //friends

            for (String friend : friends) {
                k.set(friend);
                v.set(user);
                context.write(k,v);
            }
        }
    }

    public static class CommonFriendsStepOneReducer extends Reducer<Text,Text,Text,Text> {
        @Override
        protected void reduce(Text friend, Iterable<Text> userLists, Context context) throws IOException, InterruptedException {
            StringBuffer userBuffer = new StringBuffer();
            for (Text user : userLists) {
                userBuffer.append(user).append(",");
            }
            context.write(friend,new Text(userBuffer.toString()));

        }
    }


    public static class CommonFriendsStepTwoMapper extends Mapper<LongWritable, Text,Text,Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            final String[] friendAndUsers = value.toString().split("\t");
            String friend= friendAndUsers[0];
            final String[] users = friendAndUsers[1].split(",");
            Arrays.sort(users);
            for (int i = 0; i < users.length-1; i++) {
                for (int j = i+1; j <users.length ; j++) {
                    context.write(new Text(users[i]+","+users[j]),new Text(friend));
                }

            }

        }
    }

    public static class CommonFriendsStepTwoReducer extends Reducer<Text,Text,Text,NullWritable> { //consistent with output format
        @Override
        protected void reduce(Text user_user, Iterable<Text> friends, Context context) throws IOException, InterruptedException {
            StringBuffer friendsList = new StringBuffer();
            for (Text friend : friends) {
                friendsList.append(friend).append(",");
            }
            friendsList = friendsList.deleteCharAt(friendsList.length()-1);
            String key = user_user.toString();
            key = "(["+key+"], ["+friendsList.toString()+"])";
            context.write(new Text(key), NullWritable.get());
        }
    }


    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
        String[] remainingArgs = optionParser.getRemainingArgs();
        if (remainingArgs.length != 2) { //Acceptable for several input files
            System.err.println("Usage: JF.BasicFriends <in> <out> ");
            System.exit(2);
        }
        Job job = Job.getInstance(conf, "basic friends");
        job.setJarByClass(BasicFriends.class);
        job.setMapperClass(BasicFriendsStepOneMapper.class);
        //job.setCombinerClass(CommonFriendsStepOneReducer.class);
        job.setReducerClass(CommonFriendsStepOneReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        FileInputFormat.addInputPath(job,new Path(remainingArgs[0]));

        //第一步job输出到临时目录中
        Path tempDir = new Path("basicfriends-temp-"+Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
        FileOutputFormat.setOutputPath(job,tempDir);

        job.setOutputFormatClass(TextOutputFormat.class);    //TextOutput

        if(job.waitForCompletion(true))
        {
            Job stepTwo = Job.getInstance(conf,"basicFriendsStep2");
            stepTwo.setJarByClass(BasicFriends.class);
            FileInputFormat.addInputPath(stepTwo,tempDir);
            stepTwo.setInputFormatClass(TextInputFormat.class);   //对应上面的stepOne输出格式

            stepTwo.setMapperClass(CommonFriendsStepTwoMapper.class);
            stepTwo.setReducerClass(CommonFriendsStepTwoReducer.class);

            stepTwo.setNumReduceTasks(1); //Reducer个数限定为1，表示最终输出结果文件为1

            stepTwo.setOutputKeyClass(Text.class);
            stepTwo.setOutputValueClass(Text.class);
            FileOutputFormat.setOutputPath(stepTwo,new Path(remainingArgs[1]));
            System.exit(stepTwo.waitForCompletion(true)?0:1);
        }


        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
